<!-- 流程管理-组件库管理-组件管理-新增或编辑组件信息 -->
<template>
  <div class="main-app">
    <el-page-header @back="cancel" :content="title" style="margin: 1%;"></el-page-header>
    <div style="margin-top: 25px; margin-left: 1%;">({{$t('common.title.tipLeft')}}<span style="color: red">*</span>{{$t('common.title.tipRight')}})</div>
    <el-row :gutter="40" style="margin: 10px">
      <!-- 基本信息编辑区 -->
      <el-col :span="12">
        <div style="width: 100%;">
          <el-divider content-position="left">基本信息</el-divider>
        </div>
        <el-form ref="form" :model="form" :rules="rules" style="width: 100%;" label-width="130px">
          <el-form-item :label="$t('common.label.attributeCnName')" prop="cnName" required>
            <el-input v-model="form.cnName" />
          </el-form-item>
          <el-form-item :label="$t('common.label.attributeEnName')" prop="enName" required>
            <el-input v-model="form.enName" />
          </el-form-item>
          <el-form-item :label="$t('common.label.inputType')" prop="inputType" required>
            <el-select v-model="form.inputType" :placeholder="$t('common.placeholder.pleaseSelect')" style="width: 100%;" @change="changeInputType">
              <el-option v-for="item in dataSource_inputType" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('common.label.plcAddress')" prop="plcAddress">
            <el-input v-model="form.plcAddress" />
          </el-form-item>
          <el-form-item :label="$t('common.label.paramType')" prop="paramType" required>
            <el-select v-model="form.paramType" :placeholder="$t('common.placeholder.pleaseSelect')" style="width: 100%;">
              <el-option v-for="item in dataSource_paramType" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('common.label.defaultValue')" prop="defaultValue">
            <el-input v-model="form.defaultValue" />
          </el-form-item>
          <el-form-item :label="$t('common.label.sort')" prop="sort" required>
            <el-input-number v-model="form.sort" :min="1" style="width:100%;"></el-input-number>
          </el-form-item>
          <el-form-item :label="$t('common.label.status')" required>
            <el-radio-group v-model="form.status">
              <el-radio :label="0">{{$t('common.label.enable')}}</el-radio>
              <el-radio :label="1">{{$t('common.label.disable')}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="$t('common.label.remark')" prop="remark">
            <el-input type="textarea" v-model="form.remark" :rows="4" maxlength="9999" show-word-limit />
          </el-form-item>
        </el-form>
      </el-col>
      <!-- 数据源编辑区 -->
      <el-col :span="12">
        <el-divider content-position="left">{{$t('common.label.inputDataSource')}}</el-divider>
        <el-alert :title="$t('common.prompt.info.editFormDataSource')" type="info" :closable="false" show-icon></el-alert>
        <el-form :inline="true" style="text-align:right; margin-top: 10px;">
          <div style="margin-right: 16px; margin-bottom: 10px;">
            <el-row :gutter="10">
              <el-col :span="7">
                <el-input :placeholder="$t('common.placeholder.pleaseInput')" v-model="form_param.cnName">
                  <template slot="prepend">{{$t('common.label.paramCnName')}}</template>
                </el-input>
              </el-col>
              <el-col :span="7">
                <el-input :placeholder="$t('common.placeholder.pleaseInput')" v-model="form_param.enName">
                  <template slot="prepend">{{$t('common.label.paramEnName')}}</template>
                </el-input>
              </el-col>
              <el-col :span="7">
                <el-input :placeholder="$t('common.placeholder.pleaseInput')" v-model="form_param.value">
                  <template slot="prepend">{{$t('common.label.paramValue')}}</template>
                </el-input>
              </el-col>
              <el-col :span="3">
                <el-button type="primary" icon="el-icon-plus" @click="param_ItemAdd()">{{$t('common.button.addLine')}}</el-button>
              </el-col>
            </el-row>
          </div>
        </el-form>
        <el-table id="table_param" style="width: 100%" ref="multipleTable" border height="497" tooltip-effect="dark" size="mini" :data="tableData_param">
          <el-table-column prop="cnName" :label="$t('common.label.paramCnName')" align="center" />
          <el-table-column prop="enName" :label="$t('common.label.paramEnName')" align="center" />
          <el-table-column prop="value" :label="$t('common.label.paramValue')" align="center" />
          <el-table-column :label="$t('common.label.operate')" align="center" width="100">
            <template slot-scope="scope">
              <el-button-group>
                <el-button size="mini" type="danger" @click="param_ItemDel(scope.row)">{{$t('common.button.del')}}</el-button>
              </el-button-group>
            </template>
          </el-table-column>
          <el-table-column align="center" width="50">
            <template slot-scope="scope">
              <i class="el-icon-rank handle"></i>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row style="margin-top: 30px; text-align: center">
      <el-form :inline="true" class="form-inline">
        <el-form-item>
          <el-button type="info" plain @click="cancel">{{$t('common.button.cancel')}}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="isLoading" @click="save">{{$t('common.button.save')}}</el-button>
        </el-form-item>
      </el-form>
    </el-row>
  </div>
</template>

<script>
// 引用 Sortable
import Sortable from 'sortablejs'
import {
  FlowAssemblyConfigDetail,
  FlowAssemblyConfigAttributeDetail,
  SubmitFlowAssemblyConfigAttribute,
} from "../../../../api/assembly.js";

export default {
  // 页面公共变量
  data() {
    return {
      isLoading: false,                 // 是否显示加载框
      title: "",                        // 顶部标题
      assemblyConfigId: "",             // 所属组件主键ID
      id: "",                           // 编辑数据的主键ID
      // 数据源
      tableData_param: [],              // 表格数据源-表单项数据源
      dataSource_assemblyConfig: {},    // 组件配置数据
      dataSource_inputType: [           // 输入类型数据
        { label: this.$t('common.label.textBox'), value: '10', disabled: false, },
        { label: this.$t('common.label.numberBox'), value: '20', disabled: false, },
        { label: this.$t('common.label.dropdownBox'), value: '30', disabled: false, },
        { label: this.$t('common.label.radioBox'), value: '40', disabled: false, },
      ],
      dataSource_paramType: [           // 参数类型数据
        { label: this.$t('common.label.string'), value: '10', disabled: false, },
        { label: this.$t('common.label.int'), value: '20', disabled: false, },
        { label: this.$t('common.label.decimal'), value: '30', disabled: false, },
      ],
      // 提交表单内容
      form: {
        inputType: '10',
        inputDataSource: '',
        paramType: '10',
        defaultValue: '',
        sort: 0,
        status: 0,
      },
      // 表单验证项配置
      rules: {
        cnName: [{required:true, message:this.$t('common.prompt.rules.attributeCnName'), trigger:"blur"}],
        enName: [{required:true, message:this.$t('common.prompt.rules.attributeEnName'), trigger:"blur"}],
        plcAddress: [{required:true, message:this.$t('common.prompt.rules.plcAddress'), trigger:"blur"}],
        sort: [{required:true, message:this.$t('common.prompt.rules.sort'), trigger:"blur"}],
        status: [{required:true, message:this.$t('common.prompt.rules.status'), trigger:"blur"}],
      },
      // 临时输入的参数内容
      form_param: {
        cnName: "",                       // 参数名称 (中文)
        enName: "",                       // 参数名称 (英文)
        value: "",                        // 参数值
      },
    };
  },
  // 页面创建完成事件
  async created() {
    // 接收路由传递的参数
    const { assemblyConfigId, id } = this.$route.params;

    // 动态设置标题
    if(id === undefined) {
      this.title = this.$t('common.title.addAttribute');
    } else {
      this.title = this.$t('common.title.editAttribute');
    }

    // 将接收到的数据填充至页面公共变量
    this.assemblyConfigId = assemblyConfigId;
    this.id = id;

    // 获取详情数据
    await this.init();
    await this.getDataInfo(id);

    // 挂载更改表格排序事件
    this.rowDrop();
  },
  // 页面相关方法
  methods: {
    // 初始化加载事件
    async init() {
      // 获取详情数据
      const { data } = await FlowAssemblyConfigDetail({
        Id: this.assemblyConfigId
      });
      if (data) {
        // 设置表单数据
        this.dataSource_assemblyConfig = data;
      }
    },
    // 获取详情数据
    async getDataInfo(id) {
      // 获取详情数据
      const { data } = await FlowAssemblyConfigAttributeDetail({
        Id: id
      });
      if (data) {
        // 处理部分字段
        data.status = parseInt(data.status);

        // 设置表单数据
        this.form = data;

        // 处理并填充表单项数据源内容
        if (this.form.inputDataSource !== "") {
          // 将字符串内容按指定符号分割为数组
          let dataSource = this.form.inputDataSource.split('||');

          // 循环遍历分割后数组内容
          let tempDataSource = [];
          let tempName = [];
          dataSource.forEach(item => {
            // 将当前循环节点按指定符号分割为数组
            tempDataSource = item.split('::');
            tempName = tempDataSource[0].split(';;');

            // 将当前循环节点内容填充至表格数据源
            this.tableData_param.push({
              cnName: tempName[0],
              enName: tempName[1],
              value: tempDataSource[1],
            });
          });
        }
      }
    },
    // 下拉框选择事件-表单项类型
    changeInputType (val) {
      switch (val) {
        case "20": { this.form.paramType = "20"; this.form.defaultValue = "0"; } break;
        default: { this.form.paramType = "10"; this.form.defaultValue = ""; } break;
      }

      // 附加操作：动态禁用字符串下拉选项
      let obj = this.dataSource_paramType.find(item => item.value === '10');
      if (obj) {
        obj.disabled = val === "20" ? true : false;
      }
    },
    // 参数列表-新增行
    param_ItemAdd() {
      // 参数校验
      if (this.form_param.cnName === "") {
        this.$message({ type: 'error', message: this.$t('common.prompt.rules.inputCnName') });
        return;
      }
      if (this.form_param.enName === "") {
        this.$message({ type: 'error', message: this.$t('common.prompt.rules.inputEnName') });
        return;
      }
      if (this.form_param.value === "") {
        this.$message({ type: 'error', message: this.$t('common.prompt.rules.inputValue') });
        return;
      }

      // 添加用户输入的参数内容
      this.tableData_param.push({
        cnName: this.form_param.cnName,
        enName: this.form_param.enName,
        value: this.form_param.value,
      });

      // 清空用户输入的内容, 便于下次输入
      this.form_param.cnName = "";
      this.form_param.enName = "";
      this.form_param.value = "";

      // 挂载更改表格排序事件
      this.rowDrop();
    },
    // 参数列表-删除行
    param_ItemDel(row) {
      let index = this.tableData_param.findIndex(item => { return item.id == row.id; });
      if (index >= 0) {
        this.tableData_param.splice(index, 1);
      }
    },
    // 数据行更改事件
    rowDrop() {
      //const el = document.querySelector('#table .el-table__body-wrapper tbody')
      const el = document.querySelectorAll('.el-table__body-wrapper > table > tbody')[0];
      const sortable = new Sortable(el, {
        animation: 150,
        handle: '.handle',
        ghostClass: 'blue-background-class',
        onEnd: evt => {
          // 更改数据源数组顺序
          this.tableData_param.splice(evt.newIndex, 0, this.tableData_param.splice(evt.oldIndex, 1)[0]);
          const newArray = this.tableData_param.slice(0);
          newArray.forEach((value, index) => {
            value.sort = index + 1; // 序号为index+1
            this.$set(newArray, index, value);

          	this.tableData_param = [];
          	this.$nextTick(() => {
          	  this.tableData_param = newArray ? newArray : [];
          	})
          });
          this.$nextTick(() => {
            // 保存更改至数据库
            this.updateSort(this.tableData_param);
          })
        }
      });
    },
    // 更改数据顺序
    async updateSort(tableData) {
      let tableSortData = [];
      tableData.forEach((value, index) => {
        tableSortData.push({
          Id: value.id,
          Value: value.sort.toString()
        });
      });
      //console.log(tableSortData);
    },
    // 保存数据事件
    save() {
      // 校验必填项
      this.$refs["form"].validate(async (valid) => {
        // 如果表单校验成功时执行
        if (valid) {
          // 处理用户输入的参数数据
          if (this.tableData_param.length > 0) {
            let inputDataSource = [];
            this.tableData_param.forEach(item => {
              inputDataSource.push(`${item.cnName};;${item.enName}::${item.value}`);
            });
            this.form.inputDataSource = inputDataSource.join('||');
            // console.log(this.form.inputDataSource);
            // return;
          }

          // 准备提交数据
          let data = {
            FlowAssemblyConfigAttributeData: {
              Id: this.id,
              AssemblyConfigId: this.dataSource_assemblyConfig.id,
              AssemblyConfigName: this.dataSource_assemblyConfig.cnName,
              CnName: this.form.cnName.replace(' ', ''),
              EnName: this.form.enName.replace(' ', ''),
              InputType: this.form.inputType,
              InputDataSource: this.form.inputDataSource,
              PlcAddress: this.form.plcAddress.replace(' ', ''),
              ParamType: this.form.paramType,
              DefaultValue: this.form.defaultValue.replace(' ', ''),
              Sort: this.form.sort,
              Status: this.form.status.toString(),
              Remark: this.form.remark
            }
          };

          // // 测试：查看已生成的表单内容，不提交数据
          // console.log(data)
          // return;

          // 打开加载框
          this.isLoading = true;

          // 提交数据
          const { success, msg } = await SubmitFlowAssemblyConfigAttribute(data);

          // 关闭加载框
          this.isLoading = false;

          // 显示返回结果
          if (success) {
            this.$message({ type: 'success', message: msg });
            this.$router.back();
          } else {
            this.$message({ type: 'error', message: msg });
          }
        }
      });
    },
    // 返回事件
    cancel() {
      this.$router.back();
    },
  },
};
</script>
